const Router = require('koa-router')
const { catchError, generateOk, check } = require('../../lib/check')
const { searchAccountById } = require('../../model/accounts')
const { searchArticle } = require('../../model/articles')
const { getAllReports, setReport } = require('../../model/report')

const report = new Router()

report.post("/add", async (ctx) => {
  try {
    const data = ctx.request.body
    check(data.articleId, "Params_Lost")
    check(data.content.length !== 0, "Params_Lost")
    check(data.userId, 'Params_Lost')
    check(data.type, 'Params_Lost')
    const findArticle = searchArticle(data.articleId)
    check(findArticle, 'No_Such_Article')
    const findUser = searchAccountById(data.userId)
    check(findUser, 'No_Such_User')
    const time = (new Date()).getTime().toString()
    const allReport = getAllReports()
    const reportId = "R" + allReport.length.toString().padStart(6, '0')
    const reportItem = {
      targetType: data.targetType,
      userId: data.userId,
      commentId: data.commentId,
      replyId: data.replyId,
      articleId: data.articleId,
      content: data.content,
      type: data.type,
      create_Ts: time,
      id: reportId,
      status: 1
    }
    setReport(reportItem)
    ctx.body = generateOk({ reportItem })
  } catch (e) {
    catchError(e, ctx)
  }
})

module.exports = report